package com.stark.commons.spring.core.boot.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.integration.support.locks.LockRegistry;

import com.stark.commons.spring.core.aspect.DistributedLockAspect;
import com.stark.commons.spring.core.boot.properties.DistributedLockProperties;

/**
 * 分布式锁自动配置。
 * @author Ben
 * @since 2021/11/30
 * @version 1.0.0
 */
@Configuration
public class DistributedLockAutoConfig {
	
	/***
	 * redis 分布式锁配置。
	 * @author Ben
	 * @since 2021/11/30
	 * @version 1.0.0
	 */
	@Configuration
	@ConditionalOnClass(name = "org.springframework.integration.redis.util.RedisLockRegistry")
	@EnableConfigurationProperties(DistributedLockProperties.class)
	protected static class RedisDistributedLockConfig {
		
		@Bean
	    @ConditionalOnMissingBean(LockRegistry.class)
	    public LockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory, DistributedLockProperties distributedLockProperties) {
	        String registryKey = "distributedLock";
	        if (StringUtils.isNotBlank(distributedLockProperties.getRedis().getCacheName())) {
	            registryKey = distributedLockProperties.getRedis().getCacheName() + "::" + registryKey;
	        }
	        return new RedisLockRegistry(redisConnectionFactory, registryKey);
	    }
		
		@Bean
		@ConditionalOnMissingBean(DistributedLockAspect.class)
		public DistributedLockAspect distributedLockAspect(LockRegistry lockRegistry, DistributedLockProperties distributedLockProperties) {
			return new DistributedLockAspect(lockRegistry, distributedLockProperties.getRedis().getTimeout());
		}
		
	}

}
